<?php

namespace App\Modules\Index\Services;

use App\Modules\Home\Models\Device;
use Illuminate\Support\Facades\DB;
use  App\Modules\Index\Models\Glucose;
use  App\Modules\Index\Models\Prescription;

class GlucoseService
{

    /**
     * 添加血糖
     * param array $data
     */
    public static function addGlu($data=[]){

        return Glucose::addGlu($data);
    }

    /**
     * @param array $data
     * @return mixed
     * 用户日志
     */
    public static function userGlucoseLog($data=[]){
        $where = "user_id = ".$data['user_id'];
        if($data['time']){
            $start = $data['time']." 00:00:00";
            $end = $data['time']." 23:59:59";
            $where .= " and time between '".$start."' and  '".$end."'";
        }

        $sql = 'select DATE(time) as date from in_merge_insulin WHERE  '.$where.' group by  date order by date desc';
        $res = DB::table(DB::raw("($sql ) as t"))->paginate()->toArray();
        $dataArr = object_to_array($res['data']);
        if($dataArr) {
            foreach ($dataArr as $key => $value) {
                $gw['user_id'] = $data['user_id'];
                $start = $value['date'] . ' 00:00:00';
                $end = $value['date'] . " 23:59:59";

                $info = DB::table('merge_insulin')->select('meals',DB :: raw('DATE_FORMAT(time,"%H:%i") as times'),'glucose','type','sign')->where('user_id',$data['user_id'])->whereBetween('time',[$start,$end])->orderBy('times','asc')->get()->toArray();
                $arr[$key]['date'] = $value['date'];
                $arr[$key]['info'] = $info;

            }
            unset($res['data']);
            $res['data'] = $arr;
        }

        return $res;
    }

    /**
     * @param array $data
     * @return mixed
     * 用户日志
     */
    public static function userGlucoseLogIos($data=[]){
        $where = "user_id = ".$data['user_id'];
        if($data['time']){
            $start = $data['time']." 00:00:00";
            $end = $data['time']." 23:59:59";
            $where .= " and time between '".$start."' and  '".$end."'";
        }

        $sql = 'select DATE(time) as date from in_merge_insulin WHERE  '.$where.' group by  date order by date desc';
        $res = DB::table(DB::raw("($sql ) as t"))->paginate()->toArray();
        $dataArr = object_to_array($res['data']);
        if($dataArr) {
            foreach ($dataArr as $key => $value) {
                $gw['user_id'] = $data['user_id'];
                $start = $value['date'] . ' 00:00:00';
                $end = $value['date'] . " 23:59:59";

                $info = DB::table('merge_insulin')->select('meals',DB :: raw('DATE_FORMAT(time,"%H:%i") as times'),'glucose','type','sign')->where('user_id',$data['user_id'])->whereBetween('time',[$start,$end])->orderBy('times','asc')->get()->toArray();
                $arr[$key]['date'] = $value['date'];
                $arr[$key]['info'] = $info;

            }
            unset($res['data']);
            $res['data'] = $arr;
        }

        return $res;
    }

    /**
     * 日统计
     */
    public static function dayLog($param=[]){
        //胰岛素注册时间
        $start = $param['time'].' 00:00:00';
        $end = $param['time']." 23:59:59";
        $insulinArr = DB::table('insulin')->select('id','maked_at','insulin_dosage','insulin_name_cn')->where('user_id',$param['user_id'])->whereBetween('maked_at',[$start,$end])->orderBy('maked_at')->get()->toArray();
        $info['insulin'] = object_to_array($insulinArr);
        //血糖测量时间
        $glucosenArr = DB::table('glucose')->select('id','glu','test_at','state')->where('user_id',$param['user_id'])->whereBetween('test_at',[$start,$end])->orderBy('test_at')->get()->toArray();
        $info['glucose'] = object_to_array($glucosenArr);

        return $info;
    }

    /**
     * 按日统计或者周统计
     */
    public static function  userLog($param=[]){
        $end = date('Y-m-d');

        if($param['state'] == 1) $start = date('Y-m-d',strtotime('-1week'));
        else $start = date('Y-m-d',strtotime('-1month'));

        //用户平均血糖
        $avgGlucose = DB::table('glucose')->where('user_id',$param['user_id'])->whereBetween('test_at',[$start.' 00:00:00',$end.' 23:59:59'])->avg('glu');
        $arr['avgGlucose'] = sprintf('%.1f',$avgGlucose);

        //用户平均模拟糖化
        $arr['avgSuger'] = $avgGlucose > 0? sprintf('%.1f',($avgGlucose*18 + 46.7)/28.7) : 0;

        //用户总测试数
        $arr['total'] =  DB::table('glucose')->where('user_id',$param['user_id'])->whereBetween('test_at',[$start.' 00:00:00',$end.' 23:59:59'])->count('glu');

        //正常数
        $arr['normal'] = DB::table('glucose')->where('user_id',$param['user_id'])->where('state',1)->whereBetween('test_at',[$start.' 00:00:00',$end.' 23:59:59'])->count('glu');

        //正常百分比
        $arr['normalPoint'] =  $arr['total']>0 ? sprintf('%.1f', $arr['normal']*100/ $arr['total']) : 0;

        //偏高次数
        $arr['height'] = DB::table('glucose')->where('user_id',$param['user_id'])->where('state',3)->whereBetween('test_at',[$start.' 00:00:00',$end.' 23:59:59'])->count('glu');

        //偏高百分比
        $arr['heightPoint'] = $arr['total'] > 0? sprintf('%.1f', $arr['height']*100/$arr['total']) : 0;

        //偏低次数
        $arr['down'] = DB::table('glucose')->where('user_id',$param['user_id'])->where('state',2)->whereBetween('test_at',[$start.' 00:00:00',$end.' 23:59:59'])->count('glu');

        //偏低百分比
        $arr['downPoint'] = $arr['total'] >0 ? sprintf('%.1f',$arr['down']*100/$arr['total']) : 0;

        //最高血糖值
        $arr['maxGlu'] =  DB::table('glucose')->where('user_id',$param['user_id'])->whereBetween('test_at',[$start.' 00:00:00',$end.' 23:59:59'])->max('glu');



        //最低血糖值
        $arr['minGlu'] =  DB::table('glucose')->where('user_id',$param['user_id'])->whereBetween('test_at',[$start.' 00:00:00',$end.' 23:59:59'])->min('glu');

        //餐前平均值
        $beforeMeal = DB::table('glucose')->where('user_id',$param['user_id'])->whereIn('meals',[1,3,5])->whereBetween('test_at',[$start.' 00:00:00',$end.' 23:59:59'])->avg('glu');
        $arr['beforeMeal'] = sprintf('%.1f',$beforeMeal);
        //餐后平均值
        $afterMeal = DB::table('glucose')->where('user_id',$param['user_id'])->whereIn('meals',[2,4,6])->whereBetween('test_at',[$start.' 00:00:00',$end.' 23:59:59'])->avg('glu');
        $arr['afterMeal'] = sprintf('%.1f',$afterMeal);

        //晚餐前平均值
        $beforeBed = DB::table('glucose')->where('user_id',$param['user_id'])->where('meals',7)->whereBetween('test_at',[$start.' 00:00:00',$end.' 23:59:59'])->avg('glu');
        $arr['beforeBed'] = sprintf('%.1f',$beforeBed);

        return $arr;

    }

    /**
     * 查询用户当天测量的数据
     */
    public static function dayGlucose($user_id,$start_time,$end_time){
        return Glucose::dayGlucose($user_id,$start_time,$end_time);
    }

    /**
     * 首页数据
     */
    public static function index($user_id){
        $time =  date('Y-m-d');
        $data = [];
        $data['glucose'] = Glucose::where('user_id',$user_id)->whereBetween('test_at',[$time.' 00:00:00',$time.' 23:59:59'])->orderBy('test_at','desc')->value('glu');
        $data['glucose'] = isset($data['glucose']) ? $data['glucose'] : 0;
        $data['test_at'] = Glucose::where('user_id',$user_id)->whereBetween('test_at',[$time.' 00:00:00',$time.' 23:59:59'])->orderBy('test_at','desc')->value('test_at');
        $data['state'] = Glucose::where('user_id',$user_id)->whereBetween('test_at',[$time.' 00:00:00',$time.' 23:59:59'])->orderBy('test_at','desc')->value('state');
        $data['meals'] = Glucose::where('user_id',$user_id)->whereBetween('test_at',[$time.' 00:00:00',$time.' 23:59:59'])->orderBy('test_at','desc')->value('meals');
        $data['meals'] = isset($data['meals']) ? $data['meals'] : 0;

        $is_update = Prescription::where('user_id',$user_id)->where('status',1)->orderBy('id','desc')->value('is_read');
        if($is_update == '0') $data['is_update'] = 1;
        else $data['is_update'] = 0;
        $data['warning'] = DB::table('warning')->where('user_id',$user_id)->where('is_read',0)->where('type',1)->count();
        return $data;
    }

    /**
     * 设备数据
     */
    public static function deviceData($user_id){
        $time =  date('Y-m-d');
        //查询用户是否绑定用户
        $data['is_bundled'] =DB::table('device')->where('bundled_user_id',$user_id)->where('status',1)->value('is_bundled');
        if(empty($data['is_bundled'])){
            $data['is_bundled'] = 0;
            return $data;
        }
        $info = Glucose::where('user_id',$user_id)
            ->whereBetween('test_at',[$time.' 00:00:00',$time.' 23:59:59'])
            ->where('type',2)
            ->orderBy('test_at','desc')
            ->select('id','glu','meals','test_at','state','diet','sport','remark')
            ->first();
        if($info){
            $result = $info->toArray();
            if(!empty($result['diet']) || !empty($result['sport']) || !empty($result['remark'])){
                $result = array();
            }
        }else{
            $result = array();
        }



        $data['data'] = $result;
        return $data;
    }

    /**
     * 添加设备数据
     */
    public static function deviceUpdate($id,$user_id,$data){
        return Glucose::where('id',$id)->where('user_id',$user_id)->update($data);

    }

}